package org.virbraligo.vboxjavaservice;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

public class LogMonitor extends Thread {
	static Logger logger = Logger.getLogger(LogMonitor.class.getName());
	String logFile = "";
	Date startupDate;
	String headlesspid = null;

	public LogMonitor(String vmConfigHome, Date startupDate) {
		logFile = vmConfigHome + "/logs/VBox.log";
		this.startupDate = startupDate;
		setName("LogMonitor");
	}

	public void run() {
		while (VBoxJavaService.active) {
			logger.info("LogMonitor started");
			File f = new File(logFile);
			//execute vboxmanage command first, so the logfile date is earlier than startupDate here
			if ((f.lastModified() - startupDate.getTime())<-3000) {
				s();
				continue;
			}
			readPID();
			if (headlesspid == null) {
				logger.log(Level.INFO, "headless process not created yet, wait...");
				s();
				continue;
			}
			new HeadlessProcessMonitor(headlesspid).start();
			logger.info("LogMonitor exit, start monitoring headless pid: "+headlesspid);
			break;
		}
	}

	private void readPID() {
		try {
			BufferedReader reader = new BufferedReader(new FileReader(new File(
					logFile)));
			String s = "";

			while ((s = reader.readLine()) != null) {
				if (s.indexOf("Process ID:") >= 0) {
					String[] split = s.split("Process ID:");
					headlesspid = split[1].trim();
					logger.info("Headless PID:" + headlesspid);
				}
			}
		} catch (FileNotFoundException e) {
			logger.log(Level.SEVERE, "", e);
		} catch (IOException e) {
			logger.log(Level.SEVERE, "", e);
		}
	}

	private void s() {
		try {
			sleep(2000);
		} catch (InterruptedException e) {
			logger.log(Level.SEVERE, "", e);
		}
	}

}
